﻿package com.bn.NNYY;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBUtils {
	static SQLiteDatabase sld;//SQLiteDatabase数据库
	//打开或创建数据库的方法
    public static void openOrCreateDatabase()
    {
    	try
    	{
	    	sld=SQLiteDatabase.openDatabase
	    	(
	    			"/data/data/com.bn.NNYY/mydb", //数据库所在路径
	    			null, 								//CursorFactory
	    			SQLiteDatabase.OPEN_READWRITE|SQLiteDatabase.CREATE_IF_NECESSARY //读写、若不存在则创建
	    	);
	    	String sql="create table if not exists highScore" +
	    			"( " +
	    			"score integer," +
	    			"date varchar(20)" +
	    			");";
	    	sld.execSQL(sql);
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    }
    //关闭数据库的方法
    public static void closeDatabase()
    {
    	try
    	{
	    	sld.close();
    	}
		catch(Exception e)
		{
			e.printStackTrace();
		}
    }
    //插入记录的方法
    public static void insert(int score,String date)
    {
    	try
    	{
    		openOrCreateDatabase();
        	String sql="insert into highScore values("+score+",'"+date+"');";
        	sld.execSQL(sql);
        	sld.close();
    	}
		catch(Exception e)
		{
			e.printStackTrace();
		}
    }

    //查询的方法
    public static String query(int posFrom,int length)//开始的位置，要查寻的记录条数
    {
    	StringBuilder sb=new StringBuilder();//要返回的结果
    	Cursor cur=null;
    	openOrCreateDatabase();
        String sql="select score,date from highScore order by score desc;";    	
        cur=sld.rawQuery(sql, null);
    	try
    	{
    		
        	cur.moveToPosition(posFrom);//将游标移动到指定的开始位置
        	int count=0;//当前查询记录条数
        	while(cur.moveToNext()&&count<length)
        	{
        		int score=cur.getInt(0);
        		String date=cur.getString(1);        		
        		sb.append(score);
        		sb.append("/");
        		sb.append(date);
        		sb.append("/");//将记录用"/"分隔开
        		count++;
        	}        			
    	}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			cur.close();
			closeDatabase();
		}
		//转换成字符，并返回
		return sb.toString();
    }
    //得到数据库中记录条数的方法
    public static int getRowCount()
    {
    	int result=0;
    	Cursor cur=null;
    	openOrCreateDatabase();
    	try
    	{
    		String sql="select count(score) from highScore;";    	
            cur=sld.rawQuery(sql, null);
        	if(cur.moveToNext())
        	{
        		result=cur.getInt(0);
        	}
    	}
    	catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			cur.close();
			closeDatabase();
		}
        
    	return result;
    }

}
